package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
	"weibo-mgr/cache"
	"weibo-mgr/model"
)

func List(c *gin.Context) {
	title := c.Query("title")
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	redis_key := "list_size" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	var weibo []model.WeiBo
	if cacheData == "" {
		model.DB.Debug().Where("title=?", title).Offset(offset).Limit(size).Find(&weibo)
		jsonData, _ := json.Marshal(&weibo)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &weibo)
	}
	var count int64
	model.DB.Model(&model.WeiBo{}).Count(&count)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  weibo,
		"count": count,
	})
	return
}

func Detail(c *gin.Context) {
	redis_key := "list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	var weibo model.WeiBo
	if cacheData == "" {
		model.DB.Debug().First(&weibo)
		jsonData, _ := json.Marshal(&weibo)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &weibo)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": weibo,
	})
	return
}
